// var DB = require("../lib/db_pg").DB;
var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var http_request = require('../lib/util.js').http_request;

exports.teacher_list = function(req,res){

    // 1-老师/3-主任/4-校长
    var sql_text = "SELECT case user_type ";
    sql_text = sql_text + " when 1 then '老师' ";
    sql_text = sql_text + " when 3 then '主任' ";
    sql_text = sql_text + " when 4 then '校长' end as title, b.user_name as login_name, ";
    sql_text = sql_text + " a.* FROM t_user a, t_sys_user b WHERE a.user_type in (1, 3, 4) ";
    sql_text = sql_text + " and a.id = b.user_id ";
    
    var tmp_params = [];
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by a." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    });
};


exports.teacher_add = function(req,res){
  var id = req.param('teacher_id');
  if(!id) return res.json({success:false,msg:'教师ID不能为空！'});
  var title = req.param('title');
  switch(title){
    case '校长':
      title = '4';
      break;
    case '主任':
      title = '3';
      break;
    case '老师':
      title = '1';
      break;
    default:
      break;
  }
  if(!title) return res.json({success:false,msg:'职务不能为空！'});
  var mobile = req.param('mobile');
  if(!mobile) return res.json({success:false,msg:'手机号码不能为空！'});
  var remark = req.param('remark');
  if(!remark){
    remark = "";
  }

  var db = new DB();
  var user_realname;
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) as counter from t_user a ";
      sql_text = sql_text + " where a.id = ? ";
      // console.log(sql_text);
      // tmp_params.push(mobile);
      tmp_params.push(id);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) console.log(err);
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('该教师记录已存在！');
        }
          return cb(null);
      })
    },function(cb){
        // if(err) return cb(err);
        var tmp_params = [];
        sql_text = "select user_realname from t_sys_user where user_id = ?";
        tmp_params.push(id);
        db.query(sql_text,tmp_params,function(err,datas){
          if(err) console.log(err);
          if(err) return cb(err);
          if(datas.length > 0){
            user_realname = datas[0].user_realname;
            console.log(user_realname);
            return cb(null);
          }else{
            return cb('无法查找姓名');
          }
        });
    },function(cb){
      var tmp_params = [];
      var sql_text = "insert into t_user(id,user_type,name,mobile,remark) ";
      sql_text += " values(?,?,?,?,?)"
      tmp_params.push(id);
      tmp_params.push(title);
      tmp_params.push(user_realname);
      tmp_params.push(mobile);
      tmp_params.push(remark);
      db.query(sql_text,tmp_params,function(err,datas){
        //console.log(datas);
        if(err)
          return cb(err);
        else
          return cb(null);    
      });
    }
  ],function(err){
    // if(err) return resErr(res,err);
    if (err){
        return res.json({success:false,msg:JSON.stringify(err)});
    }      
    return res.json({success:true,msg:'修改成功！'});
  })
}

exports.teacher_upd = function(req,res){
  var id = req.param('teacher_id');
  if(!id) return res.json({success:false,msg:'教师ID不能为空！'});
  var title = req.param('title');
  switch(title){
    case '校长':
      title = '4';
      break;
    case '主任':
      title = '3';
      break;
    case '老师':
      title = '1';
      break;
    default:
      break;
  }
  if(!title) return res.json({success:false,msg:'职务不能为空！'});
  var mobile = req.param('mobile');
  if(!mobile) return res.json({success:false,msg:'手机号码不能为空！'});
  var remark = req.param('remark');
  if(!remark){
    remark = "";
  }

  var db = new DB();
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) as counter from t_user a ";
      sql_text = sql_text + " where a.mobile = '" + mobile + "' ";
      sql_text = sql_text + " and a.id <> '" + id + "' " ;
      // console.log(sql_text);
      // tmp_params.push(mobile);
      // tmp_params.push(id);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) console.log(err);
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('手机号码重复！');
        }
        return cb(null);
      })
    },function(cb){
      var tmp_params = [];
      var sql_text = "update t_user set mobile=? ";
      tmp_params.push(mobile);
      if(title){
        sql_text += ", user_type = ? ";
        tmp_params.push(title);
      } 
      if(remark){
          sql_text += " , remark = ? ";
          tmp_params.push(remark);
      }
      sql_text += " where id = ?; ";
      tmp_params.push(id);
      db.query(sql_text,tmp_params,function(err,datas){
        //console.log(datas);
        if (err){
          return cb(err);
        }
        return cb(null);
      })
    }
  ],function(err){
    if(err)
      return res.json({success:false,msg:JSON.stringify(err)});
    else
      return res.json({success:true,msg:'修改成功！'});
  })
}

exports.teacher_del = function(req,res){
    var id = req.param('id');
    if(!id) return res.json({success: false, msg: '用户ID不能为空'});
    
    var db = new DB();
    var sql_text = 'delete from t_user where id = ?;';
    
    var tmp_params = [];
    tmp_params.push(id);
    
    db.query(sql_text, tmp_params, function(err, datas){
        console.log(datas);
        if(err){
            return resErr(res, err);
        }
        return res.json({success: true, msg: '删除成功'});
    });
}

exports.teacher_search_name = function(req,res){
    var sql_text;
    var db = new DB();
    var name = req.param('name');

    if(!name)
      sql_text = sql_text = "SELECT u.* FROM t_user u WHERE user_type in (1, 3, 4)";
    else
      sql_text = "SELECT u.* FROM t_user u WHERE name LIKE ? and user_type in (1, 3, 4)";

    var tmp_params = [];
    tmp_params.push(name);
    
    console.log(sql_text);
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    }); 
};

exports.get_leaders = function(req, res){
    var sql_text;
    var db = new DB();

    sql_text = sql_text = "SELECT u.* FROM t_user u WHERE user_type=3"; //3是主任
    
    var tmp_params = [];
    
    console.log(sql_text);
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    }); 
};

exports.get_teachers = function(req, res){
  var sql_text;
  var db = new DB();

  sql_text = sql_text = "SELECT u.* FROM t_user u WHERE user_type=1"; //1是老师
  
  var tmp_params = [];
  
  console.log(sql_text);
  
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
  if(req.param("sort")){
      sql_text += " order by u." + req.param("sort");
      if(req.param("dir")){
          sql_text += " " + req.param("dir");
      }
  }
  
  var db = new DB();
  db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
      if(err) return resErr(res, err);

      console.log(result);
      return res.json(result);
  }); 
};
